<template>
	<view class="login_content">
		<view class="header_img">
			<image style="width: 500rpx; height: 450rpx;" mode="scaleToFill" src="../../static/login.png" />
		</view>

		<view class="form_content">
			<uni-easyinput placeholderStyle="font-size: 30rpx;" style="margin-bottom: 40rpx;" prefixIcon="phone" type="text" v-model="formData.uid" placeholder="请输入手机号码" />
			<uni-easyinput placeholderStyle="font-size: 30rpx;" style="margin-bottom: 40rpx;" type="password" prefixIcon="locked" v-model="formData.password" placeholder="请输入登陆密码" />


			<view style="display: flex; align-items: center;justify-content: space-between; margin-bottom: 40rpx;">
				<view class="http_config" @click="openRegister">
					<text class="iconfont icon-saoma"></text>
					<view>扫码配置网络</view>
				</view>
				<checkbox-group @click="formData.rememberPsw = !formData.rememberPsw">
					<label style="line-height: 40rpx;color: #9b9b9b;font-size: 24rpx;">
						<checkbox value="psw" :checked='formData.rememberPsw'
							color="#FFAC60" />记住账号密码
					</label>
				</checkbox-group>
			</view>
			<!--  -->
			<button hover-class="hover_btn" @click="bindLogin">登录</button>
			<button hover-class="hover_btn" @click="handleRegister">注册</button>
			<view  style="color: #9b9b9b; font-size: 24rpx; display: flex; align-items: center; justify-content: space-between;">
				<!-- <radio-group v-model="formData.LoginType" @change="changeLoginType">
					<radio :checked="formData.LoginType == 'stores'" value="stores">销售商</radio>
					<radio style="margin-left: 40rpx;" :checked="formData.LoginType == 'user'" value="user">订购商</radio>
				</radio-group> -->
				<text @click="handleForgetPsw">忘记密码</text>
			</view>
			<view style="color: #9b9b9b; font-size: 24rpx; margin-top: 20rpx; text-align: right;">
				<text>当前版本：{{ Version || '1.0.0' }}</text>
			</view>
		</view>

		<view class="login_footer">
			<view>义乌市弘兆信息技术有限公司</view>
			<view @click="makePhoneCall">销售热线：17855898445</view>
		</view>

		<uni-popup ref="configPopup" :mask-click="false" type="bottom">
			<view class="config_popup">
				<view class="config_title">服务/更新地址配置</view>
				<view class="config_item">
					<text>服务地址:</text>
					<input type="text" v-model="baseUrl" />
					<text @click="updateAdd('baseUrl')" class="iconfont icon-saoma"></text>
				</view>

				<view class="config_item">
					<text>更新地址:</text>
					<input type="text" v-model="updateUrl" />
					<text @click="updateAdd('updateUrl')" class="iconfont icon-saoma"></text>
				</view>

				<view class="config_button">
					<button @click="setHttpSave" hover-class="hover_save">确认</button>
					<button @click="setHttpClose" >取消</button>
				</view>
			</view>
		</uni-popup>

	</view>
</template>
<script>
	import Http from '@/service/api'
	import Base64 from "../../utils/base.js";
	const base64 = new Base64()
	export default {
		data() {
			return {
				token: '',
				customId: uni.getStorageSync('customId'),
				dk: '',

				loading: false,
				qx: '',

				baseUrl: '', // 服务地址  jinmiaompro.ywhzsoft.com/JinMiaoPbkdTest
				updateUrl: '', // 更新地址
				Version: uni.getStorageSync('bbh'),
				formData: {
					rememberPsw: true,
					LoginType: uni.getStorageSync('LoginType') || 'stores',
				},
				rules: {
					uid: {
						rules:[
							{
								required: true,
								errorMessage: '请输入手机号码',
							},
						],
					},
					password: {
						rules:[
							{
								required: true,
								errorMessage: '请输入登陆密码',
							},
						],
					}
				},
			};
		},
		computed: {
			disabledCom() {
				if (this.uid && this.password) {
					return false
				} else {
					return true
				}
			}
		},

		onLoad() {
			//获取缓存账号
			this.dk = this.$baseURL
			this.Version = uni.getStorageSync('bbh')
			const uid = uni.getStorageSync('uid');
			const password = uni.getStorageSync('password');

			if (uid && password) {
				this.formData.uid = uid;
				this.formData.password = password;
			} else {
				this.formData.uid = ""; // 1001
				this.formData.password = ""; // 123
			}
			// 订购商 账号:13919769856  密码：1234
			// 销售商 账号:1001  		密码：123

			// uni.setStorageSync(`baseUrl`, 'jinmiaompro.ywhzsoft.com/JinMiaoPbkdTest');
			// this.checkAccount('jinmiaompro.ywhzsoft.com/JinMiaoPbkdTest') // 扫描配置码的

			console.log('== 配置码 baseUrl : ', uni.getStorageSync('baseUrl') )
			// 删掉
			let url = 'http://hzserver.ywhzsoft.com:8888/update/ScPadUpdate/04712/Update'
			// uni.setStorageSync(`updateUrl`, url);
			// uni.setStorageSync('bbh', '1.0.17')
			// uni.removeStorageSync(`updateUrl`);
			// uni.removeStorageSync(`bbh`);

			console.log('== 版本号 ', uni.getStorageSync('bbh'))
			// 删掉

			if (!uni.getStorageSync('bbh')) {
				uni.setStorageSync('bbh', '1.0.0')
			}
		},
		methods: {
			changeLoginType(e) {
				this.formData.LoginType = e.detail.value;
			},
			bindLogin() {
				if (this.formData.uid == '') {
					uni.showToast({
						title: '请输入账号',
						icon: 'none'
					});
					return;
				}
				if (this.formData.password == '') {
					uni.showToast({
						title: '请输入密码',
						icon: 'none'
					});
					return;
				}

				let param = {
					uid: this.formData.uid,
					password: this.formData.password,
					customId: this.customId,
					LoginType: this.formData.LoginType,
				}
				console.log('== param ', param)

				if (!this.customId) {
					uni.showToast({
						title: '请先扫描配置码',
						icon: 'none'
					});
					return
				}
				
				Http.login(param).then(r => {
					uni.setStorageSync('token', r.token)
					let token = r.token
					let splitToken = token.split('.')
					let info = splitToken[1].replace(/-/g, '+').replace(/_/g, '/')
					let jwt = base64.decode(info.toString())
					let arr = ((jwt.replace(/\{|}/g,'')).replace(/\"/g, "")).split(',')
					arr.some(val => {
						if(val.indexOf('movePrice') != -1) {
							let tempArr = val.split(':')
							uni.setStorageSync('movePrice',tempArr[1])
							return true
						}
					})

					//登录成功将用户名密码存储到用户本地
					if (this.formData.rememberPsw) { //用户勾选“记住密码”
						uni.setStorageSync('uid', this.formData.uid);
						uni.setStorageSync('password', this.formData.password);
						uni.setStorageSync('loginUserName', r.loginUserName);
						uni.setStorageSync('LoginType', r.LoginType);
					} else { //用户没有勾选“记住密码”
						uni.removeStorageSync('uid');
						uni.removeStorageSync('password');
						uni.removeStorageSync('loginUserName');
					}

					uni.setStorageSync('loginData',r)

					if (r.LoginType == 'stores') {
						uni.switchTab({
							url: '../../salesPages/index/index'
						})
					} else {
						uni.redirectTo({
							url: '../../orderPages/index/index'
						})
					}

				}).catch( err => {
					console.log('== err ', err)
					uni.showToast({
						title: err.message,
						icon: 'none'
					});
				})
					
			},
			openRegister() {
                this.updateUrl = uni.getStorageSync('updateUrl') ? uni.getStorageSync('updateUrl') : ''
                this.baseUrl = uni.getStorageSync('baseUrl') ? uni.getStorageSync('baseUrl') : ''
                this.$refs.configPopup.open('center')
                return
				uni.scanCode({
					onlyFromCamera: false,
					scanType: ['qrCode'],
					success: res => {

					}
				})
			},
			handleRegister() {
				uni.navigateTo({
					url: './registered'
				})
			},
			handleForgetPsw() {
				uni.navigateTo({
					url: './forgotPassword'
				})
			},

			// 扫描配置网络
            setHttpSave() {
				if (!this.baseUrl) {
					uni.showToast({
						title: '请输入服务地址',
						icon: 'none'
					});
					return
				}
                uni.setStorageSync('updateUrl', this.updateUrl);
                uni.setStorageSync('baseUrl', this.baseUrl);
				this.checkAccount(this.baseUrl)
                this.$refs.configPopup.close()
            },
            setHttpClose() {
                this.updateUrl = uni.getStorageSync('updateUrl') ? uni.getStorageSync('updateUrl') : ''
                this.baseUrl = uni.getStorageSync('baseUrl') ? uni.getStorageSync('baseUrl') : ''
                this.$refs.configPopup.close()
            },
            updateAdd(type) {
                uni.scanCode({
					onlyFromCamera: false,
					scanType: ['qrCode', 'barCode'],
					success: res => {
                        if (res.result) {
                            this[type] = res.result
							uni.setStorageSync(`${type}`, res.result);
							if ( type == 'baseUrl' ) {
								this.checkAccount(res.result)
							}
							this.$refs.configPopup.close()
                        }
					}
				})
            },
			checkAccount(result) { // 检验账套码
				Http.checkAccount({
					qrcode:result
				}).then(r => {  
					console.log('== r ', r)
					uni.showToast({
						title:'配置成功',
						icon:'none',
						duration:1500  
					})
					// store.isCheck = true
					this.customId = r.customId
					uni.setStorageSync('customId', r.customId)
				}).catch(err => {
					console.log('== err ', err)
					if (err.errMsg) return
					uni.showToast({
						title:err.message,
						icon:'none',
						duration:1500
					})
					// store.isCheck = false
					this.customId = ''
					uni.setStorageSync('customId','')
				})
			},

            // 底部拨打电话
			makePhoneCall() {
				uni.makePhoneCall({
					phoneNumber: '17855898445' //仅为示例
				});
			},
			Random() {
				var time = new Date();
				var num = time.getTime() + Date.now().toString(36);
				return num;
			}

		},
	}
</script>

<style lang="scss" scoped>
	.login_content {
		width: 100vw;
		height: 100vh;
		display: flex;
		flex-direction: column;

		.header_img {
			display: flex;
			align-items: center;
			justify-content: center;
			width: 100%;
			height: 40%;
		}

		.form_content {
			flex: 1;
			background: #fff;
			padding: 20rpx;

			/deep/.uni-easyinput__content-input {
				height: 80rpx;
			}

			.http_config {
				display: flex;
				align-items: center;
				background: #bbb;
				padding: 10rpx 15rpx;
				color: #fff;
				border-radius: 20rpx;
				font-size: 20rpx;
				.iconfont {
					font-size: 20rpx;
					margin-right: 10rpx;
				}
			}

			/deep/.content-clear-icon {
				font-size: 40rpx !important;
			}
			/deep/.uni-input-input {
				font-size: 30rpx;
			}

			button {
				display: flex;
				align-items: center;
				justify-content: center;
				background: #f9a94d;
				height: 60rpx;
				color: #fff;
				font-size: 30rpx;
				margin-bottom: 25rpx;
				border-radius: 30rpx;
			}

			.hover_btn {
				background: #e09845;
			}
		}

		.login_footer {
			color: #9e9e9e;
			font-size: 15rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			height: 80rpx;
		}
	}

    .config_popup {
        width: 80vw;
        background: #fff;
        border-radius: 15rpx;
        padding: 20rpx;

        .config_title {
            margin-bottom: 40rpx;
            font-size: 40rpx;
        }

        .config_item {
            display: flex;
            align-items: center;
            margin-bottom: 20rpx;
            font-size: 30rpx;
            input {
                flex: 1;
                border: 1rpx solid #ccc;
                padding: 10rpx 20rpx;
                margin: 0 20rpx;
            }
            .iconfont {
                font-size: 50rpx;
            }
        }

        .config_button {
            display: flex;
            align-items: center;
            margin-top: 40rpx;

            button {
                display: flex;
                align-items: center;
                justify-content: center;
				font-size: 30rpx;
                width: 200rpx;
                height: 45rpx;
            }

            button:nth-child(1) {
                background: #009fd9;
                color: #fff;
            }
            .hover_save {
                background: #047fac !important;
                
            }
        }
    }
</style>